package com.test.card.service.impl;

import com.test.card.bean.CardInfo;
import com.test.card.bean.UserInfo;
import com.test.card.contants.UserContants;
import com.test.card.enums.ApiResponseEnum;
import com.test.card.exception.CardException;
import com.test.card.repository.CardInfoRepository;
import com.test.card.repository.UserInfoRepository;
import com.test.card.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@Transactional
public class UserInfoServiceImpl implements IUserInfoService
{
    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private CardInfoRepository cardInfoRepository;

    /**
     * 卡激活
     * @param request
     * @param state
     * @return
     */
    @Override
    public Integer acitvateCard(UserInfo request, Integer state) {
        Integer userCount = userInfoRepository.findBycardNo(request.getPhone());
        if (userCount > 0) {
            throw new CardException(ApiResponseEnum.USER_ALREADY_HAVE);
        }

        request.setPoint(UserContants.DEFAULT_POINT);
        request.setCreateTime(LocalDateTime.now());
        Integer count =userInfoRepository.save(request);

        if(count > 0){
            CardInfo cardInfo = new CardInfo();
            cardInfo.setUpdateTime(LocalDateTime.now());
            if (state == UserContants.ACTIVATE) {
                cardInfo.setState(state);
            }
            else {
                throw new CardException(ApiResponseEnum.STATE_ERROR);
            }
            cardInfo.setCardNo(request.getCardNo());

            count = cardInfoRepository.updateCardState(cardInfo);
            if (count <= 0) {
                throw new CardException(ApiResponseEnum.NO_CARD);
            }
        }
        return count;
    }
}
